﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Qiniu.Http;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.JSON;
using Qiniu.RS;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;

public class QiniuContext
{
    private string AccessKey;
    private string SecretKey;
    private string Bucket;
    private string Domain;
    private static QiniuContext instance;
    public static QiniuContext Instance
    {
        get
        {
            if (instance == null)
                instance = new QiniuContext();
            return instance;
        }
    }
    public QiniuContext()
    {
        //AccessKey
        AccessKey = WebConfigurationManager.AppSettings["qiniu_accesskey"];
        //SecretKey
        SecretKey = WebConfigurationManager.AppSettings["qiniu_secretkey"];
        //BUCKET
        Bucket = WebConfigurationManager.AppSettings["qiniu_bucket"];
        //Domain
        Domain = WebConfigurationManager.AppSettings["qiniu_domain"];
        Qiniu.Common.Config.AutoZone(AccessKey, Bucket, true);
        Qiniu.JSON.JsonHelper.JsonSerializer = new AnotherJsonSerializer();
        Qiniu.JSON.JsonHelper.JsonDeserializer = new AnotherJsonDeserializer();
    }

    /// <summary>
    /// 简单上传-上传小文件
    /// </summary>
    public string UploadFile(string localFile, string saveKey)
    {
        // 生成(上传)凭证时需要使用此Mac
        Mac mac = new Mac(AccessKey, SecretKey);
        string bucket = Bucket;
        // 上传策略，参见 
        // https://developer.qiniu.com/kodo/manual/put-policy
        PutPolicy putPolicy = new PutPolicy();
        // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
        putPolicy.Scope = bucket + ":" + saveKey;
        //putPolicy.Scope = bucket;
        // 上传策略有效期(对应于生成的凭证的有效期)          
        putPolicy.SetExpires(3600);
        // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
        //putPolicy.DeleteAfterDays = 1;
        // 生成上传凭证，参见
        // https://developer.qiniu.com/kodo/manual/upload-token            
        string jstr = putPolicy.ToJsonString();
        string token = Auth.CreateUploadToken(mac, jstr);
        UploadManager um = new UploadManager();
        HttpResult result = um.UploadFile(localFile, saveKey, token);
        //Console.WriteLine(result);
        return result.ToString();
    }

    public string GetUrl(string saveKey)
    {
        return Domain + saveKey;
    }

    public string Delete(string saveKey)
    {
        Mac mac = new Mac(AccessKey, SecretKey);
        BucketManager bucketManager = new BucketManager(mac);
        HttpResult httpResult = bucketManager.Delete(Bucket, saveKey);
        return httpResult.ToString();
    }
}

public class AnotherJsonSerializer : IJsonSerializer
{
    // 实现此接口的JSON序列化方法
    public string Serialize<T>(T obj) where T : new()
    {
        var settings = new JsonSerializerSettings();
        settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        settings.NullValueHandling = NullValueHandling.Ignore;
        return JsonConvert.SerializeObject(obj, settings);
    }
}
public class AnotherJsonDeserializer : IJsonDeserializer
{
    // 实现此接口的JSON反序列化方法
    public bool Deserialize<T>(string str, out T obj) where T : new()
    {
        obj = default(T);
        bool ok = true;
        try
        {
            obj = JsonConvert.DeserializeObject<T>(str);
        }
        catch (System.Exception)
        {
            ok = false;
        }
        return ok;
    }
}
